package com.dz.interception;

import com.alibaba.fastjson.JSON;
import com.dz.util.Result;
import com.dz.util.SYS;
import com.dz.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

//地陪登录拦截器
public class GuideLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 设置响应编码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        String method=request.getMethod();
        if ("OPTIONS".equalsIgnoreCase(method)){
            return true;
        }
        //获取token
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);
        System.out.println("---------------"+token);
        //验证token
        if (token == null || !TokenUtil.verify(token)){
            //response.setStatus(401);
            Result result = new Result(401, "验证失败", null);
            String json = JSON.toJSONString(result);
            response.getWriter().write(json);
            //返回结果
            return false;
        }

        // 验证角色是否为地陪
        String role = TokenUtil.getRole(token);
        if (!SYS.ROLE_GUIDE.equals(role)) {
            Result result = new Result(403, "权限不足，需要地陪权限", null);
            String json = JSON.toJSONString(result);
            response.getWriter().write(json);
            return false;
        }

        //放行
        return true;
    }
}
